package com.jinxin.platform.cdinfogo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-12-28
 * @Author: Lingnan
 **/
@Slf4j
public class FileUtils {
    public static final String TYPE_JPG = "jpg";
    public static final String TYPE_GIF = "gif";
    public static final String TYPE_PNG = "png";
    public static final String TYPE_BMP = "bmp";
    public static final String TYPE_UNKNOWN = "unknown";

    public static final String FORMAT_FILE_NAME = "%d.%s";

    private static byte[] b;

    /**
     *
     * @description: 根据文件流判断图片类型
     * @author: Jeff
     * @date: 2019年12月7日
     * @param fis 文件输入流
     * @return
     */
    public static String getPicType(InputStream fis) {
        // 读取文件的前几个字节来判断图片格式
        b = new byte[4];
        try {
            fis.read(b, 0, b.length);
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                return TYPE_JPG;
            } else if (type.contains("89504E47")) {
                return TYPE_PNG;
            } else if (type.contains("47494638")) {
                return TYPE_GIF;
            } else if (type.contains("424D")) {
                return TYPE_BMP;
            } else {
                return TYPE_UNKNOWN;
            }
        } catch (IOException e) {
            log.error(e.toString());
        }
        return null;
    }

    /**
     *
     * @description: byte数组转换成16进制字符串
     * @author: Jeff
     * @date: 2019年12月7日
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     *
     * @description: 判断文件夹是否存在，不存在则创建
     * @author: Jeff
     * @date: 2019年12月7日
     * @param dir
     */
    public static void isDirPathExist(File dir) {
        // 判断文件夹是否存在
        if (dir.isDirectory()) {
            log.info(dir + "文件夹已存在");
        } else {
            log.info(dir + "文件夹不存在");
            dir.mkdir();
            log.info("创建文件夹" + dir);
        }
    }

    /**
     *
     * @description: 从服务器获得图片输入流InputStream,并写到本地磁盘
     * @author: Jeff
     * @date: 2019年12月7日
     */
    public static void saveImageToDisk(InputStream inputStream, String diskPath) {
        // 根据文件流判断图片类型，此处不要关闭流,要不然下方获取不到输入流
        String picType = FileUtils.getPicType(inputStream);
        log.info("图片格式为：" + picType);
        String fileName = String.format(FORMAT_FILE_NAME, new Date().getTime(), picType);
        log.info("图片名字为：" + fileName);
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            File dirFile = new File(diskPath);
            // 判断文件夹是否存在，不存在则创建
            FileUtils.isDirPathExist(dirFile);
            fileOutputStream = new FileOutputStream(new File(dirFile, fileName));
            // 首先写入判断图片格式的前几个字节
            fileOutputStream.write(b, 0, b.length);
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info(fileName + "写到本地磁盘完成");
    }
}
